load("@rules_distroless//distroless:defs.bzl", "passwd")
load("@rules_oci//oci:defs.bzl", "oci_image")
load("@rules_pkg//:pkg.bzl", "pkg_tar")
load("@rules_rust//rust:defs.bzl", "rust_binary")
load("//rs/tests:system_tests.bzl", "oci_tar")

package(default_visibility = ["//rs:system-tests-pkg"])

DEPENDENCIES = [
    # Keep sorted.
    "@crate_index//:axum",
    "@crate_index//:clap",
    "@crate_index//:hyper",
    "@crate_index//:hyper-util",
    "@crate_index//:rand",
    "@crate_index//:rustls",
    "@crate_index//:rustls-pemfile",
    "@crate_index//:serde_json",
    "@crate_index//:tokio",
    "@crate_index//:tokio-rustls",
    "@crate_index//:tower",
]

rust_binary(
    name = "httpbin",
    srcs = ["src/main.rs"],
    target_compatible_with = ["@platforms//os:linux"],  # requires libssh that does not build on Mac OS
    visibility = [
        "//rs:system-tests-pkg",
        "//rs/pocket_ic_server:__pkg__",
    ],
    deps = DEPENDENCIES,
)

pkg_tar(
    name = "httpbin_image_homedir",
    srcs = [":httpbin"],
    package_dir = "/home/httpbin",
)

## Create a layer with a httpbin user

passwd(
    name = "passwd",
    entries = [
        dict(
            gecos = ["root"],
            gid = 0,
            home = "/root",
            shell = "/usr/bin/bash",
            uid = 0,
            username = "root",
        ),
        dict(
            gecos = ["httpbin_user"],
            gid = 1002,
            home = "/home/httpbin",
            shell = "/usr/bin/bash",
            uid = 1002,
            username = "httpbin",
        ),
    ],
)

## An intermediate image with the passwd file and empty directories.

oci_image(
    name = "httpbin_image_base",
    base = "//rs/tests:ubuntu_test_runtime_image_src",
    tags = ["manual"],
    target_compatible_with = [
        "@platforms//os:linux",
    ],
    tars = [
        ":passwd",
    ],
)

## The final image we export for tests
oci_image(
    name = "httpbin_image_src",
    base = ":httpbin_image_base",
    entrypoint = ["/home/httpbin/httpbin"],
    tags = ["manual"],
    target_compatible_with = [
        "@platforms//os:linux",
    ],
    tars = [":httpbin_image_homedir"],
    user = "httpbin",
    workdir = "/home/httpbin",
)

oci_tar(
    name = "httpbin.tar",
    image = ":httpbin_image_src",
    repo_tags = ["httpbin:image"],
)
